package com.baiye.template.filter;


import com.alibaba.fastjson.JSONObject;
import com.baiye.template.common.R;
import com.baiye.template.pojo.Role;
import com.baiye.template.pojo.User;

import com.baiye.template.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author GUOZHIPENG
 * @version 1.0
 * @date 2021/9/10 18:37
 */
public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JwtLoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }


//    @Override
//    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
//        User user=null;
//        try {
//             user = JSONObject.parseObject(request.getInputStream(),User.class);
//            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword()));
//        } catch (IOException e) {
//            try {
//                response.setContentType("application/json;charset=utf-8");
//                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                PrintWriter out = response.getWriter();
//                Map<String, Object> map = new HashMap<>();
//                map.put("code", HttpServletResponse.SC_UNAUTHORIZED);
//                map.put("message", "账号或密码错误！");
//                out.write(new ObjectMapper().writeValueAsString(map));
//                out.flush();
//                out.close();
//            } catch (Exception e1) {
//                e1.printStackTrace();
//            }
//            throw new RuntimeException(e);
//        }
//
//    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        User user = new User();
        user.setUsername(authResult.getName());
        user.setRoles((List<Role>) authResult.getAuthorities());
        String token = JwtUtils.generateTokenExpireInMinutes(user,24*60);
        response.addHeader("Authorization", "MyToken " + token);
        Gson gson = new Gson();
        response.getWriter().write(gson.toJson(new R<>().ok(user)));
    }
}
